package org.vt.ece3574.pictoslider.menus;

import java.util.Collections;
import java.util.List;

import org.vt.ece3574.pictoslider.HighScoreManager;
import org.vt.ece3574.pictoslider.HighScoreManager.Difficulty;
import org.vt.ece3574.pictoslider.HighScoreObject;
import org.vt.ece3574.pictoslider.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

/**
 * This class represents the activity which displays all of the user's high
 * scores. As of right now, this is a dummy screen.
 * 
 * @author Justin Scarborough
 */
public class HighScoreScreen extends Activity {

	// Layout Parameters
	private static final int PADDING = 5;
	private static final int TEXT_SIZE = 25;
	private static final int TEXT_GRAVITY = Gravity.CENTER_VERTICAL
			| Gravity.LEFT;
	private static final float ITEM_WEIGHT = 1;

	/**
	 * String key passed to SharedPreferences. Represents an integer index for
	 * the current tab.
	 */
	private static final String CURRENT_TAB = "CurrentTab";
	/**
	 * String key passed to SharedPreferences. Represents a boolean. True if the
	 * high scores are sorted by moves, false if by time.
	 */
	private static final String BY_MOVES = "ByMoves";

	/**
	 * The TabHost in this activity.
	 */
	private TabHost host = null;
	/**
	 * True if high scores are sorted by Moves, false if by Times.
	 */
	private boolean byMoves = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Themes.onActivityCreateSetTheme(this);
		Themes.onActivityCreateSetContentView(this, R.layout.highscoretabbed);

		// Initialize byMoves to value stored in SharedPreferences
		byMoves = getSharedPreferences(CURRENT_TAB, 0).getBoolean(BY_MOVES,
				false);

		// Set the text color for the TextViews and RadioButtons in each tab.
		((TextView) findViewById(R.id.easyText)).setTextColor(Themes
				.textColor(this));
		((TextView) findViewById(R.id.mediumText)).setTextColor(Themes
				.textColor(this));
		((TextView) findViewById(R.id.hardText)).setTextColor(Themes
				.textColor(this));
		((TextView) findViewById(R.id.crazyText)).setTextColor(Themes
				.textColor(this));
		((RadioButton) findViewById(R.id.easyTime)).setTextColor(Themes
				.textColor(this));
		((RadioButton) findViewById(R.id.easyMoves)).setTextColor(Themes
				.textColor(this));
		((RadioButton) findViewById(R.id.mediumTime)).setTextColor(Themes
				.textColor(this));
		((RadioButton) findViewById(R.id.mediumMoves)).setTextColor(Themes
				.textColor(this));
		((RadioButton) findViewById(R.id.hardTime)).setTextColor(Themes
				.textColor(this));
		((RadioButton) findViewById(R.id.hardMoves)).setTextColor(Themes
				.textColor(this));
		((RadioButton) findViewById(R.id.crazyTime)).setTextColor(Themes
				.textColor(this));
		((RadioButton) findViewById(R.id.crazyMoves)).setTextColor(Themes
				.textColor(this));

		// Load and sort the high scores into each tab as appropriate.
		if (byMoves)
			sortByMoves(null);
		else
			sortByTime(null);

		// Create the TabHost and TabSpecs.
		doSetupTabs();
	}

	/**
	 * OnClickListener for the Time RadioButton in each tab. Loads the high
	 * scores from memory and sorts them by time.
	 * 
	 * @param v
	 *            - The View which was clicked.
	 */
	public void sortByTime(View v) {
		// Let the activity know how the scores are sorted, and check the
		// appropriate RadioButton in each Tab's RadioGroup.
		byMoves = false;
		((RadioGroup) findViewById(R.id.easyGroup)).check(R.id.easyTime);
		((RadioGroup) findViewById(R.id.mediumGroup)).check(R.id.mediumTime);
		((RadioGroup) findViewById(R.id.hardGroup)).check(R.id.hardTime);
		((RadioGroup) findViewById(R.id.crazyGroup)).check(R.id.crazyTime);

		// Get the high scores for each difficulty and put them into each tab's
		// TableLayout.
		for (Difficulty d : Difficulty.values()) {
			HighScoreManager hsm = new HighScoreManager(getApplicationContext());
			List<HighScoreObject> highScores = hsm
					.getHighScoreListForDifficulty(d, false);
			setUpTabWithHighScores(highScores, d.id());
		}
	}

	/**
	 * OnClickListener for the Moves RadioButton in each tab. Loads the high
	 * scores from memory and sorts them by moves.
	 * 
	 * @param v
	 *            - The View which was clicked.
	 */
	public void sortByMoves(View v) {
		// Let the activity know how the scores are sorted, and check the
		// appropriate RadioButton in each Tab's RadioGroup.
		byMoves = true;
		((RadioGroup) findViewById(R.id.easyGroup)).check(R.id.easyMoves);
		((RadioGroup) findViewById(R.id.mediumGroup)).check(R.id.mediumMoves);
		((RadioGroup) findViewById(R.id.hardGroup)).check(R.id.hardMoves);
		((RadioGroup) findViewById(R.id.crazyGroup)).check(R.id.crazyMoves);

		// Get the high scores for each difficulty and put them into each tab's
		// TableLayout.
		for (Difficulty d : Difficulty.values()) {
			HighScoreManager hsm = new HighScoreManager(getApplicationContext());
			List<HighScoreObject> highScores = hsm
					.getHighScoreListForDifficulty(d, true);
			setUpTabWithHighScores(highScores, d.id());
		}
	}

	/**
	 * This function puts each tab into the TabHost, and sets the Current Tab.
	 */
	private void doSetupTabs() {
		// Retrieve the TabHost, and run its setup() method so it is ready to
		// have Tabs added.
		host = (TabHost) findViewById(R.id.toplevel);
		host.setup();

		// Create a new Tab for each difficulty.
		for (Difficulty d : Difficulty.values()) {
			TabSpec ts = host.newTabSpec(d.asString());
			ts.setContent(d.frameId());
			ts.setIndicator(d.asString());
			host.addTab(ts);
		}
		host.setCurrentTab(getSharedPreferences(CURRENT_TAB, 0).getInt(
				CURRENT_TAB, 1));
	}

	/**
	 * Using the given HighScoreObject list, populates the TableLayout pointed
	 * to by the given Resource Id with High Scores.
	 * 
	 * @param highScores
	 *            - A list of HighScoreObjects to be made into High Score
	 *            TextViews and ImageViews.
	 * @param tableLayoutId
	 *            - The Resource Id of the table layout to place the produced
	 *            views into.
	 */
	private void setUpTabWithHighScores(List<HighScoreObject> highScores,
			int tableLayoutId) {

		// Get the TableLayout from the Resource Id, empty it, and sort the high
		// scores.
		TableLayout table = (TableLayout) findViewById(tableLayoutId);
		table.removeAllViews();
		Collections.sort(highScores);

		int count = 1;
		for (HighScoreObject hs : highScores) {

			// Create table row
			TableRow temp = new TableRow(getBaseContext());
			temp.setLayoutParams(new TableLayout.LayoutParams(
					TableLayout.LayoutParams.MATCH_PARENT,
					TableLayout.LayoutParams.MATCH_PARENT));

			// Create textview for place (i.e. "1)" for first place)
			TextView place = new TextView(getApplicationContext());
			place.setLayoutParams(new TableRow.LayoutParams(
					TableRow.LayoutParams.MATCH_PARENT,
					TableRow.LayoutParams.MATCH_PARENT, ITEM_WEIGHT));
			place.setText(count + ") ");
			place.setTextSize(TEXT_SIZE);
			place.setGravity(TEXT_GRAVITY);
			place.setPadding(PADDING, PADDING, PADDING, PADDING);
			place.setTextColor(Themes.textColor(this));
			temp.addView(place);

			// Create textview for time taken to solve puzzle
			TextView time = new TextView(getApplicationContext());
			time.setLayoutParams(new TableRow.LayoutParams(
					TableRow.LayoutParams.MATCH_PARENT,
					TableRow.LayoutParams.MATCH_PARENT, ITEM_WEIGHT));
			time.setText(hs.getTimeAsString());
			time.setTextSize(TEXT_SIZE);
			time.setGravity(TEXT_GRAVITY);
			time.setPadding(PADDING, PADDING, PADDING, PADDING);
			time.setTextColor(Themes.textColor(this));
			temp.addView(time);

			// Create textview for number of moves to solve puzzle
			TextView moves = new TextView(getApplicationContext());
			moves.setLayoutParams(new TableRow.LayoutParams(
					TableRow.LayoutParams.MATCH_PARENT,
					TableRow.LayoutParams.MATCH_PARENT, ITEM_WEIGHT));
			moves.setText("" + hs.getMoves());
			moves.setTextSize(TEXT_SIZE);
			moves.setGravity(TEXT_GRAVITY);
			moves.setPadding(PADDING, PADDING, PADDING, PADDING);
			moves.setTextColor(Themes.textColor(this));
			temp.addView(moves);

			// Create imageview for picture in puzzle
			ImageView image = new ImageView(getApplicationContext());
			image.setLayoutParams(new TableRow.LayoutParams(
					TableRow.LayoutParams.MATCH_PARENT,
					TableRow.LayoutParams.MATCH_PARENT, ITEM_WEIGHT));
			image.setImageBitmap(hs.getImage());
			image.setPadding(PADDING, PADDING, PADDING, PADDING);
			temp.addView(image);

			// Add table row to table
			table.addView(temp);

			// Increment count
			count++;
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		getSharedPreferences(CURRENT_TAB, 0).edit()
				.putInt(CURRENT_TAB, host.getCurrentTab()).commit();
		getSharedPreferences(CURRENT_TAB, 0).edit()
				.putBoolean(BY_MOVES, byMoves).commit();
	}
}